package com.example.quartzdemo.observer;

import com.example.quartzdemo.Entity.QuartzBean;
import com.example.quartzdemo.constans.BaseConstant;
import com.example.quartzdemo.memory.CacheFactory;
import com.example.quartzdemo.memory.LocalCache;
import com.example.quartzdemo.memory.LocalCacheList;
import com.example.quartzdemo.memory.LocalCacheTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.CollectionUtils;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * 观察者
 *
 * @author yeyangtao
 * @since 2022/6/20 15:34
 */
@Slf4j
public class JobChangerWatcher implements Observer {

    @Override
    public void update(Observable o, Object arg) {
        LocalCache localCache = CacheFactory.getLocalCache(LocalCacheTypeEnum.LIST);

        List<QuartzBean> jobList = localCache.getAll();
        if (!CollectionUtils.isEmpty(jobList)) {
            Resource resource = new ClassPathResource(BaseConstant.BACKUP_PATH);
            // 序列化
            try (FileOutputStream fos = new FileOutputStream(resource.getFile().getPath());
                 ObjectOutputStream oos = new ObjectOutputStream(fos)) {
                oos.writeObject(jobList);
            } catch (Exception e) {
                log.info("序列化失败：" + e.getMessage());
            }
        }
        log.info("观察者已更新");
    }
}
